import { BadgeType } from "../../model/BadgeType";
import EventType from "../../model/EventType";
import EventManage from "../event/EventManage";
import PoolObj from "../pool/PoolObj";
import UIUtils from "../utils/UIUtils";

/**
 * 红点样式
 * 
 * 普通红点，数字红点，动态红点
 */
export type BADGEVIEW = "SIGN" | "NUMBER" | "DYNAMIC";

/**
 * 红点事件/委托
 */
export interface BadgeAction {
    caller?: any;
    ages?: any[];
    method?(ages?: any): number;
}

export class BadgeNode {

    private _groups = new Set<BadgeType>();

    /**节点值 */
    value: number = 0;

    /**节点内容 */
    key: BadgeType;

    /**节点类型 */
    type: BADGEVIEW;

    /**节点委托方法 */
    action: BadgeAction;

    constructor(type?: BadgeType) {
        this.key = type;
    }

    addGropu(group: BadgeType) {
        this._groups.add(group);
    }

    update(v: number = 0) {
        let oldV = this.value;
        this.value = this.actionConst;
        if (oldV != this.value) {
            EventManage.I.event(EventType.BADGE_CHANGE, this.key)
        }
    }

    get groups(): BadgeType[] {
        return Array.from(this._groups);
    }

    get groupSize() {
        return this._groups.size;
    }

    get flag() {
        return this.value != null && this.value > 0;
    }

    get actionConst(): number {
        if (!this.action) {
            return 0;
        }

        if (!this.action.caller) {
            return this.action.method(this.action.ages);
        }
        return this.action.method.apply(this.action.caller, this.action.ages);

    }


}

export class BadgeView {
    private static viewKey = "BADGEVIEW_POOL";

    private viewArray: Laya.Sprite[];

    type: BadgeType;

    //标识，方便批量移除
    caller: any;


    add(v: Laya.Sprite) {

        if (v == null) return;

        !this.viewArray && (this.viewArray = []);

        if (this.find(v)) return

        this.viewArray.push(v);
    }

    remove(v: Laya.Sprite) {
        // v.badge = false;
        return this.viewArray.remove(v);
    }

    find(view: Laya.Sprite) {
        return this.viewArray.find(v => v === view)
    }

    isEmpty() {
        return !this.viewArray || this.viewArray.length <= 0;
    }

    get viewArr(): ReadonlyArray<Laya.Sprite> {
        return this.viewArray;
    }

    set badge(v: boolean) {
        for (let elm of this.viewArray) {
            // elm.badge = v;
            UIUtils.setBadge(elm, v)
        }
    }

    static create(): BadgeView {
        return PoolObj.getItemByClass(BadgeView.viewKey, BadgeView);
    }

    static recover(node: BadgeView) {
        node.caller = null;
        node.viewArray = null;
        node.type = null;
        PoolObj.recover(BadgeView.viewKey, node);
    }
}